/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2015年3月6日         Root.Lu
 */

package com.coocaa.app.gamecenter.framework;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.app.CoocaaApplication.DeviceModeMidType;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.uipackage.ThemeActivity;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.tianci.appstore.R;
import com.tianci.appstore.ui.widget.TipToast;
import com.tianci.appstore.utils.SkyConstants;

import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

public abstract class GameCenterActivity extends ThemeActivity {
    private static final int _gc_common_pagetitle_x = SkyConstants.Div(54);
    private static final int _gc_common_pagetitle_y = SkyConstants.Div(62);

    private static final int _gc_common_pagetitle_text_x = SkyConstants.Dpi(114);
    private static final int _gc_common_pagetitle_text_y = SkyConstants.Dpi(54);
    private static final int _gc_common_pagetitle_textsize = SkyConstants.Dpi(40);

    public static final String INTENT_TITLE_KEY = "GameCenterActivity.Intent.title";
    private long current = 0;
    protected FrameLayout mMainlayout = null;
    protected ImageView mLoading = null;

    private boolean enableTitleView = true;

    private TextView errorTextView = null;
    private Timer mTimer = null;
    private static boolean bInit = false;

    private static String thisUUID = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isLoadingData = false;
        current = System.currentTimeMillis();
        mMainlayout = new FrameLayout(this);
        mMainlayout.setBackgroundResource(R.drawable.ui_sdk_app_bg);
        setContentView(mMainlayout);
        initActivity(this);
        doLoad();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        doLoad();
    }

    private boolean isLoadingData = false;

    protected final void doLoad() {
        thisUUID = UUID.randomUUID().toString();
        final String currentUUID = thisUUID;
        LogUtils.d("UUID", "thisUUID:" + thisUUID + "  current:" + current);
        if (isLoadingData)
            return;
        final View contentView = createContentView();
        if (hasCache()) {
            mMainlayout.removeAllViews();
            initTitleView();
            mMainlayout.addView(contentView);
            updateContentView();
        } else {

            mMainlayout.removeAllViews();
            CoocaaApplication.post(new Runnable() {
                @Override
                public void run() {
                    try {

                        if (isLoadingData)
                            return;
                        isLoadingData = true;
                        loadData();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                LogUtils.d("UUID", "drawui currentUUID:" + currentUUID + "  current:" + current);
                                if (currentUUID.equals(thisUUID)) {
                                    if (current != 0) {
                                        initTitleView();
                                        mMainlayout.addView(contentView);
                                        updateContentView();
                                    }
                                    isLoadingData = false;
                                }
                            }
                        });
                    } catch (final Exception e) {
                        setLoadDataErrorMsg(e.getMessage());
                    } finally {
                        isLoadingData = false;
                    }
                }
            });
        }
    }

    private static synchronized void initActivity(Context context) {
        if (bInit)
            return;
        bInit = true;
    }

    protected void enableTitleView(boolean enable) {
        enableTitleView = enable;
    }

    @Override
    protected void onDestroy() {
        DeviceModeMidType deviceType = LiteAppApplication.getDeviceModeMidType();
        if (deviceType != null
                && (deviceType.skytype.toLowerCase().contains("a43") || deviceType.skytype
                .toLowerCase().contains("a55"))) {
            long end = System.currentTimeMillis();
            LogUtils.d("log", "gamecenter000  time:" + (int) (end - current));
            LogAPIForAppStore.AModuleUseTimelong(
                    "com.coocaa.app.gamecenter.pages.home.GameMainActivity", current, end,
                    (int) (end - current));
            try {
                Thread.currentThread().sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        current = 0;
        hideloading();
        mMainlayout.removeAllViews();
        super.onDestroy();
    }

    private ImageView imgTitle = null;
    private TextView titleView = null;

    private void initTitleView() {
        if (enableTitleView) {
            LinearLayout layoutTitle = new LinearLayout(this);
            layoutTitle.setGravity(Gravity.LEFT | Gravity.CENTER);
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            params.leftMargin = _gc_common_pagetitle_x;
            params.topMargin = _gc_common_pagetitle_y;
            mMainlayout.addView(layoutTitle, params);

            imgTitle = new ImageView(this);
            imgTitle.setImageResource(R.drawable.gc_common_pagetitle);
            LinearLayout.LayoutParams imgTitleParams = new LinearLayout.LayoutParams(
                    SkyConstants.Div(22), SkyConstants.Div(25));
            layoutTitle.addView(imgTitle, imgTitleParams);
            // mMainlayout.addView(imgTitle, params);

            titleView = new TextView(this);
            titleView.setText("    ");
            titleView.setTextSize(_gc_common_pagetitle_textsize);
            layoutTitle.addView(titleView);
        }
        // mMainlayout.addView(titleView, params);
    }

    protected int getMarginLeft() {
        return 0;
    }

    protected void showloading() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mLoading == null) {
                    mLoading = new ImageView(GameCenterActivity.this);
                    mLoading.setBackgroundResource(R.anim.game_center_loading);
                    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                            SkyConstants.Div(180), SkyConstants.Div(180), Gravity.CENTER);
                    mMainlayout.addView(mLoading, params);
                    params.leftMargin = getMarginLeft();
                    mLoading.setVisibility(View.GONE);
                }

                if (mLoading.getVisibility() != View.VISIBLE) {
                    mLoading.setVisibility(View.VISIBLE);
                    AnimationDrawable drawable = (AnimationDrawable) mLoading.getBackground();
                    if (drawable != null) {
                        drawable.start();
                    }
                }

                mLoading.bringToFront();
            }
        });

    }

    protected void hideloading() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mLoading != null) {
                    AnimationDrawable drawable = (AnimationDrawable) mLoading.getBackground();
                    if (drawable != null) {
                        drawable.stop();
                    }
                    mLoading.setVisibility(View.GONE);
                }
            }
        });
    }

    protected void recycleLoading() {
        if (mLoading != null) {
            Drawable drawable = mLoading.getBackground();
            if (drawable != null) {
                drawable.setCallback(null);
            }
            mMainlayout.removeView(mLoading);
            mLoading = null;
        }
    }

    protected boolean hasCache() {
        return false;
    }

    protected final void updateTitle(final String title) {
        if (!enableTitleView)
            return;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (titleView != null)
                        titleView.append(title);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    protected void setLoadDataErrorMsg(final String error) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (errorTextView == null) {
                    errorTextView = new TextView(GameCenterActivity.this);
                    errorTextView.setTextColor(Color.WHITE);
                    errorTextView.setTextSize(SkyConstants.Dpi(48));
                    mMainlayout.addView(errorTextView, new FrameLayout.LayoutParams(
                            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER));
                }
                errorTextView.setText(error);
            }
        });
    }

    public void startSlowNetTimerDalay(int delay) {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TipToast.getInstance(GameCenterActivity.this).showNetSlowToast();
                    }
                });
            }
        }, delay);
    }

    public void cancelSlowNetTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    public boolean checkNet() {
        if (Android.isNetConnected(this)) {
            return true;
        }
        return false;
    }


    protected abstract View createContentView();

    protected abstract void loadData() throws Exception;

    protected abstract void updateContentView();

    private static final String APP_SESSION_KEY = "55a9c5e267e58ec213009a74";

    @Override
    protected String getAppSessionKey() {
        return APP_SESSION_KEY;
    }
}
